<template>
  <div v-if="isReady">
    <slot />
  </div>
  <div v-else class="auth-loading">
    <el-loading-directive
      v-loading="true"
      element-loading-text="正在验证登录状态..."
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useAuthStore } from '@/stores/authStore'
import { ElMessage } from 'element-plus'

const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()

const isReady = ref(false)

onMounted(async () => {
  await checkAuthStatus()
})

/**
 * 检查认证状态
 */
const checkAuthStatus = async () => {
  try {
    // 不需要认证的页面
    const publicPages = ['/login', '/register']
    const isPublicPage = publicPages.includes(route.path)
    
    if (isPublicPage) {
      // 公开页面，直接显示
      isReady.value = true
      return
    }
    
    // 需要认证的页面，检查登录状态
    if (!authStore.isLoggedIn) {
      // 未登录，跳转到登录页
      ElMessage.warning('请先登录')
      router.replace('/login')
      return
    }
    
    // 已登录，验证token有效性
    const isValid = await authStore.validateAuth()
    if (isValid) {
      isReady.value = true
    } else {
      // token无效，跳转到登录页
      ElMessage.warning('登录已过期，请重新登录')
      router.replace('/login')
    }
    
  } catch (error) {
    console.error('认证检查失败:', error)
    ElMessage.error('认证检查失败，请重新登录')
    router.replace('/login')
  }
}
</script>

<style scoped>
.auth-loading {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 9999;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
